<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <text class="nav-title">我的日记</text>
      </view>
    </view>
    
    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 搜索框 -->
      <view class="search-section">
        <view class="search-wrapper">
          <text class="search-icon">🔍</text>
          <input
            v-model="searchKeyword"
            placeholder="搜索日记内容..."
            @input="debounceSearch"
            @confirm="handleSearch"
            class="search-input"
          />
        </view>
      </view>
      
      <!-- 筛选标签 -->
      <view class="filter-tags" v-if="hasActiveFilters">
        <scroll-view scroll-x>
          <view class="tags-container">
            <view 
              class="filter-tag" 
              v-if="diaryStore.filters.categoryId"
              @click="clearCategoryFilter"
            >
              <text>{{ getCategoryName(diaryStore.filters.categoryId) }}</text>
              <text class="clear-tag">×</text>
            </view>
            
            <view 
              class="filter-tag" 
              v-for="tagId in diaryStore.filters.tagIds" 
              :key="tagId"
              @click="removeTagFilter(tagId)"
            >
              <text>{{ getTagName(tagId) }}</text>
              <text class="clear-tag">×</text>
            </view>
            
            <view 
              class="filter-tag" 
              v-if="diaryStore.filters.mood"
              @click="clearMoodFilter"
            >
              <text>{{ diaryStore.filters.mood }}</text>
              <text class="clear-tag">×</text>
            </view>
            
            <view class="clear-all-tag" @click="clearAllFilters">
              <text>清除筛选</text>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 日记列表 -->
      <scroll-view 
        scroll-y 
        class="diary-scroll" 
        @scrolltolower="loadMore"
        enable-back-to-top
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="refreshData"
      >
        <view class="diary-list">
          <!-- 日记项 -->
          <view 
            class="diary-item" 
            v-for="diary in diaryStore.filteredDiaries" 
            :key="diary.id"
            @click="goToDiaryDetail(diary.id)"
            @longpress="showDiaryMenu(diary)"
          >
            <!-- 日记头部 -->
            <view class="diary-header">
              <view class="header-left">
                <text class="diary-title">{{ diary.title }}</text>
                <view class="diary-meta">
                  <text class="meta-date">{{ formatDate(diary.diaryDate) }}</text>
                  <text class="meta-time">{{ formatTime(diary.createdAt) }}</text>
                </view>
              </view>
              <view class="header-right">
                <text class="more-icon" @click.stop="showDiaryMenu(diary)">⋯</text>
              </view>
            </view>
            
            <!-- 日记内容预览 -->
            <view class="diary-content">
              <text class="content-text">{{ diary.content }}</text>
            </view>
            
            <!-- 日记图片 -->
            <view class="diary-images" v-if="diary.images && diary.images.length > 0">
              <view class="images-grid">
                <image 
                  v-for="(image, index) in diary.images.slice(0, 3)" 
                  :key="index"
                  :src="image.thumbnail || image.url" 
                  mode="aspectFill"
                  class="image-item"
                  @click.stop="previewImage(diary.images, index)"
                />
                <view v-if="diary.images.length > 3" class="more-images">
                  <text class="more-text">+{{ diary.images.length - 3 }}</text>
                </view>
              </view>
            </view>
            
            <!-- 日记标签 -->
            <view class="diary-footer" v-if="diary.category || diary.tags || diary.mood || diary.weather">
              <view class="footer-tags">
                <!-- 分类 -->
                <view class="tag category-tag" v-if="diary.category">
                  <text class="tag-text">{{ diary.category.name }}</text>
                </view>
                
                <!-- 标签 -->
                <view 
                  class="tag normal-tag" 
                  v-for="tag in diary.tags?.slice(0, 2)" 
                  :key="tag.id"
                >
                  <text class="tag-text">{{ tag.name }}</text>
                </view>
                
                <view v-if="diary.tags && diary.tags.length > 2" class="more-tags">
                  <text class="more-text">+{{ diary.tags.length - 2 }}</text>
                </view>
              </view>
              
              <view class="footer-meta">
                <text class="meta-item" v-if="diary.mood">{{ diary.mood }}</text>
                <text class="meta-item" v-if="diary.weather">{{ diary.weather }}</text>
              </view>
            </view>
          </view>
          
          <!-- 加载更多 -->
          <view class="load-more" v-if="diaryStore.hasMore && !diaryStore.loading">
            <text class="load-more-text">上拉加载更多</text>
          </view>
          
          <!-- 加载中 -->
          <view class="load-more" v-if="diaryStore.loading">
            <text class="loading-text">⏳</text>
            <text class="load-more-text">加载中...</text>
          </view>
          
          <!-- 没有更多 -->
          <view class="load-more" v-if="!diaryStore.hasMore && diaryStore.diaries.length > 0">
            <text class="load-more-text no-more">没有更多日记了</text>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="diaryStore.diaries.length === 0 && !diaryStore.loading">
          <text class="empty-icon">📝</text>
          <text class="empty-text">还没有日记</text>
          <button class="empty-btn" @click="goToWrite">开始写日记</button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 写日记按钮 -->
    <view class="fab-container">
      <view class="fab-btn" @click="goToWrite">
        <text class="fab-icon">✏️</text>
      </view>
    </view>
    
    <!-- 日记操作菜单 -->
    <view class="modal-overlay" v-if="showActionModal" @click="showActionModal = false">
      <view class="action-modal" @click.stop>
        <view class="action-item" @click="editDiary">
          <text class="action-text">编辑</text>
        </view>
        <view class="action-item delete" @click="deleteDiary">
          <text class="action-text">删除</text>
        </view>
        <view class="action-item cancel" @click="showActionModal = false">
          <text class="action-text">取消</text>
        </view>
      </view>
    </view>
    
    <!-- 底部导航栏 -->
    <TabBar :current="1" />
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { getDiariesAPI, deleteDiaryAPI } from '@/api/diary'
import { getCategoriesAPI } from '@/api/category'
import { getTagsAPI } from '@/api/tag'
import { extractResponseData } from '@/utils/index'
import { formatDateTime, formatDate, debounce } from '@/utils/index'
import TabBar from '@/components/TabBar.vue'

export default {
  name: 'DiaryListPage',
  components: {
    TabBar
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore,
      formatDate,
      debounceSearch: debounce((value) => {
        // 防抖搜索
      }, 500)
    }
  },
  data() {
    return {
      searchKeyword: '',
      refreshing: false,
      showActionModal: false,
      selectedDiary: null
    }
  },
  computed: {
    hasActiveFilters() {
      const filters = this.diaryStore.filters
      return filters.categoryId || 
             filters.tagIds.length > 0 || 
             filters.mood || 
             filters.keyword
    },
    
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    }
  },
  onLoad() {
    this.initPage()
  },
  onShow() {
    // 只有在日记列表为空时才刷新
    if (this.diaryStore.diaries.length === 0 && this.userStore.isLogin) {
      this.refreshData()
    }
  },
  onReachBottom() {
    this.loadMore()
  },
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 加载基础数据
      await this.loadBasicData()
      
      // 加载日记列表
      await this.loadDiaries()
    },
    
    async loadBasicData() {
      try {
        // 并行加载分类和标签
        const [categoriesRes, tagsRes] = await Promise.all([
          getCategoriesAPI(),
          getTagsAPI()
        ])
        
        const categoriesData = extractResponseData(categoriesRes)
        const tagsData = extractResponseData(tagsRes)
        
        this.diaryStore.setCategories(categoriesData || [])
        this.diaryStore.setTags(tagsData || [])
      } catch (error) {
        console.error('加载基础数据失败:', error)
      }
    },
    
    async loadDiaries(isLoadMore = false) {
      if (this.diaryStore.loading) return
      
      try {
        this.diaryStore.setLoading(true)
        
        const page = isLoadMore ? this.diaryStore.currentPage + 1 : 1
        
        const params = {
          page,
          limit: this.diaryStore.pageSize,
          ...this.diaryStore.filters
        }
        
        const res = await getDiariesAPI(params)
        
        const responseData = extractResponseData(res)
        const diaries = responseData.diaries || []
        const pagination = responseData.pagination || {}
        
        this.diaryStore.setDiaries(diaries, isLoadMore)
        this.diaryStore.setPagination(page, pagination.totalPages ? page < pagination.totalPages : false)
        
      } catch (error) {
        console.error('加载日记失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.diaryStore.setLoading(false)
      }
    },
    
    async refreshData() {
      this.refreshing = true
      this.diaryStore.resetState()
      await this.loadDiaries()
      this.refreshing = false
    },
    
    async loadMore() {
      if (!this.diaryStore.hasMore || this.diaryStore.loading) return
      await this.loadDiaries(true)
    },
    
    // 搜索处理
    handleSearch() {
      this.diaryStore.setFilters({ keyword: this.searchKeyword.trim() })
      this.diaryStore.resetState()
      this.loadDiaries()
    },
    
    // 筛选处理
    handleFilterConfirm(filters) {
      this.diaryStore.setFilters(filters)
      this.diaryStore.resetState()
      this.loadDiaries()
    },
    
    // 清除筛选
    clearAllFilters() {
      this.diaryStore.clearFilters()
      this.diaryStore.resetState()
      this.loadDiaries()
    },
    
    clearCategoryFilter() {
      this.diaryStore.setFilters({ categoryId: null })
      this.diaryStore.resetState()
      this.loadDiaries()
    },
    
    removeTagFilter(tagId) {
      const tagIds = this.diaryStore.filters.tagIds.filter(id => id !== tagId)
      this.diaryStore.setFilters({ tagIds })
      this.diaryStore.resetState()      
      this.loadDiaries()
    },
    
    clearMoodFilter() {
      this.diaryStore.setFilters({ mood: null })
      this.diaryStore.resetState()
      this.loadDiaries()
    },
    
    // 获取分类名称
    getCategoryName(categoryId) {
      const category = this.diaryStore.categoryMap[categoryId]
      return category ? category.name : '未知分类'
    },
    
    // 获取标签名称
    getTagName(tagId) {
      const tag = this.diaryStore.tagMap[tagId]
      return tag ? tag.name : '未知标签'
    },
    
    // 格式化时间
    formatTime(dateStr) {
      if (!dateStr) return ''
      return formatDateTime(dateStr, 'HH:mm')
    },
    
    // 显示日记菜单
    showDiaryMenu(diary) {
      this.selectedDiary = diary
      this.showActionModal = true
    },
    
    // 预览图片
    previewImage(images, current) {
      const urls = images.map(img => img.url)
      uni.previewImage({
        urls,
        current: current || 0
      })
    },
    
    // 跳转到写日记页面
    goToWrite() {
      if (!this.userStore.checkLoginStatus()) return
      uni.switchTab({
        url: '/pages/diary/edit'
      })
    },
    
    // 跳转到日记详情页面
    goToDiaryDetail(id) {
      uni.navigateTo({
        url: `/pages/diary/detail?id=${id}`
      })
    },
    
    // 编辑日记
    editDiary() {
      if (!this.selectedDiary) return
      this.showActionModal = false
      
      // 设置编辑状态
      this.diaryStore.setEditingDiary(this.selectedDiary.id)
      
      // 跳转到编辑页面
      uni.switchTab({
        url: '/pages/diary/edit'
      })
    },
    
    // 删除日记
    async deleteDiary() {
      if (!this.selectedDiary) return
      
      const result = await uni.showModal({
        title: '确认删除',
        content: '确定要删除这篇日记吗？',
        confirmText: '删除',
        confirmColor: '#ff4d4f'
      })
      
      if (!result.confirm) return
      
      try {
        await deleteDiaryAPI(this.selectedDiary.id)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.showActionModal = false
        this.refreshData()
      } catch (error) {
        console.error('删除日记失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-top: var(--status-bar-height, 44rpx);
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 40rpx;
  height: 88rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
}

.nav-right {
  padding: 8rpx;
}

.filter-icon {
  font-size: 32rpx;
  color: #ffffff;
}

.page-content {
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
  padding-left: 40rpx;
  padding-right: 40rpx;
  padding-bottom: 160rpx;
}

.search-section {
  margin-bottom: 32rpx;
}

.search-wrapper {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 40rpx;
  padding: 24rpx 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.search-icon {
  font-size: 28rpx;
  color: #999999;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  border: none;
  outline: none;
}

.filter-tags {
  margin-bottom: 32rpx;
}

.tags-container {
  display: flex;
  gap: 16rpx;
  padding-right: 40rpx;
}

.filter-tag {
  display: flex;
  align-items: center;
  background-color: #1890ff;
  color: #ffffff;
  padding: 8rpx 16rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  white-space: nowrap;
}

.clear-tag {
  margin-left: 8rpx;
  font-size: 28rpx;
}

.clear-all-tag {
  background-color: #ff4d4f;
  color: #ffffff;
  padding: 8rpx 16rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  white-space: nowrap;
}

.diary-scroll {
  height: 100%;
}

.diary-list {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.diary-item {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.diary-item:active {
  transform: scale(0.98);
}

.diary-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
}

.header-left {
  flex: 1;
  margin-right: 16rpx;
}

.diary-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 12rpx;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.diary-meta {
  display: flex;
  gap: 16rpx;
}

.meta-date {
  font-size: 26rpx;
  color: #666666;
}

.meta-time {
  font-size: 24rpx;
  color: #999999;
}

.header-right {
  padding: 8rpx;
}

.more-icon {
  font-size: 32rpx;
  color: #cccccc;
}

.diary-content {
  margin-bottom: 24rpx;
}

.content-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.diary-images {
  margin-bottom: 24rpx;
}

.images-grid {
  display: flex;
  gap: 16rpx;
}

.image-item {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
}

.more-images {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-text {
  font-size: 24rpx;
  color: #666666;
}

.diary-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16rpx;
}

.footer-tags {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.tag {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
}

.category-tag {
  background-color: #1890ff;
  color: #ffffff;
}

.normal-tag {
  background-color: #f0f0f0;
  color: #666666;
}

.tag-text {
  font-size: 22rpx;
}

.more-tags {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  background-color: #f0f0f0;
}

.footer-meta {
  display: flex;
  gap: 16rpx;
}

.meta-item {
  background-color: #f9f9f9;
  color: #666666;
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  padding: 40rpx;
}

.loading-text {
  font-size: 32rpx;
}

.load-more-text {
  font-size: 26rpx;
  color: #666666;
}

.no-more {
  color: #999999;
}

.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  display: block;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 48rpx;
  display: block;
}

.empty-btn {
  background-color: #1890ff;
  color: #ffffff;
  border: none;
  border-radius: 40rpx;
  padding: 24rpx 48rpx;
  font-size: 28rpx;
}

.empty-btn::after {
  border: none;
}

.fab-container {
  position: fixed;
  right: 40rpx;
  bottom: 200rpx;
  z-index: 999;
}

.fab-btn {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
}

.fab-icon {
  font-size: 48rpx;
  color: #ffffff;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.filter-modal {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin: 40rpx;
  width: calc(100% - 80rpx);
  max-height: 80vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  font-size: 48rpx;
  color: #cccccc;
}

.modal-body {
  padding: 40rpx;
}

.filter-tip {
  text-align: center;
  color: #999999;
  font-size: 28rpx;
}

.action-modal {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin: 40rpx;
  overflow: hidden;
}

.action-item {
  padding: 32rpx 40rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item.delete .action-text {
  color: #ff4d4f;
}

.action-item.cancel {
  margin-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-text {
  font-size: 32rpx;
  color: #333333;
}

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .nav-bar {
  background: linear-gradient(135deg, #404040 0%, #2d2d30 100%);
}

.theme-dark .nav-title {
  color: #e8e8e8;
}

.theme-dark .search-wrapper {
  background-color: #252526;
  border-color: #404040;
}

.theme-dark .search-input {
  color: #e8e8e8;
}

.theme-dark .diary-item {
  background-color: #252526;
}

.theme-dark .diary-title {
  color: #e8e8e8;
}

.theme-dark .meta-date,
.theme-dark .meta-time,
.theme-dark .content-text,
.theme-dark .load-more-text,
.theme-dark .empty-text {
  color: #b3b3b3;
}

.theme-dark .normal-tag,
.theme-dark .meta-item {
  background-color: #404040;
  color: #b3b3b3;
}

.theme-dark .filter-tag {
  background-color: #404040;
  color: #b3b3b3;
}

.theme-dark .clear-all-tag {
  background-color: #ff4d4f;
}

.theme-dark .fab-btn {
  background: linear-gradient(135deg, #404040 0%, #2d2d30 100%);
}

.theme-dark .action-modal,
.theme-dark .filter-modal {
  background-color: #252526;
}

.theme-dark .modal-title,
.theme-dark .action-text {
  color: #e8e8e8;
}

.theme-dark .modal-header {
  border-bottom-color: #404040;
}

.theme-dark .action-item {
  border-bottom-color: #404040;
}

.theme-dark .action-item.cancel {
  border-top-color: #404040;
}
</style> 